<style scoped>
.red {
  color: #EE0A24;
}

.grey {
  color: #bbb;
}

.container {
  width: 100%;
  height: 100%;
  background: #fff;
}
</style>

<template>
  <div class="container">
    <van-nav-bar @click-left="back">
      <van-icon size="20" name="arrow-left" slot="left" color="rgb(150, 151, 153)"/>
      <p slot="title" style="font-size: 14px">账号密码登录</p>
    </van-nav-bar>
    <van-form>
      <van-field v-model="username" name="username" label="手机号" placeholder="请输入手机号" autocomplete="off"/>
      <van-field v-model="password" type="password" name="password" label="密码" placeholder="请输入密码" autocomplete="off">
      </van-field>
      <div style="margin: 16px;">
        <van-button @click="login" round block color="#F70D00" native-type="submit">登录</van-button>
      </div>
    </van-form>
    <van-row>
      <van-col span="12" style="text-align: left">
        <router-link to="/register" tag="div">
          <van-button size="small" color="#fff" style="margin-right: 10px">
            <template v-slot:default><span class="grey">手机快速注册</span></template>
          </van-button>
        </router-link>
      </van-col>
    </van-row>
  </div>
</template>

<script>
import Vue from 'vue';
import {mapMutations} from 'vuex'
import {NavBar, Col, Row, Form, Field, Button} from 'vant';
import {requestToLogin} from "../../api/user";

Vue.use(NavBar)
Vue.use(Col)
Vue.use(Row)
Vue.use(Form)
Vue.use(Field)
Vue.use(Button)

export default {
  name: "LoginWithPwd",
  data() {
    return {
      username: '',
      password: '',
    }
  },
  methods: {
    ...mapMutations({
      changeLogin: 'user/changeLogin',
      changeActive: 'tabs/doActive'
    }),
    login() {
      if (!this.checkForm()) {
        this.$notify("输入不得为空！")
        return;
      }
      requestToLogin({username: this.username, password: this.password}).then(res => {
        // 由于密码输入错误，后端返回的数据没有data，可能解构失败，这里进行判断分治
        let {token, userid,freeze} = res.data.data ? res.data.data : res.data
        if (res.data.code == 200&&!freeze) {
          this.$toast({
            type: 'success',
            message: '登录成功'
          })
          this.changeLogin({token, userid})
          this.$router.back()
        } else {
          console.log(res)
          if(freeze){
            this.$notify("账号被冻结")
          }else{
            this.$notify("账号或密码错误")
          }
        }
      })
    },
    checkForm() {
      return this.password && this.username;
    },
    back() {
      this.$router.push('/')
      this.changeActive(0)
    }
  }
}
</script>
